package top.plgxs.admin.filter;

import com.alibaba.druid.DbType;
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.JdbcParameter;
import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy;
import com.alibaba.druid.sql.SQLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 打印执行sql过滤器
 *
 * @author Style
 * @version 1.0
 * @date 2022/2/13
 **/
@Slf4j
@Component
public class DruidSqlLogFilter extends FilterEventAdapter {

    public DruidSqlLogFilter() {
    }

    @Override
    public boolean preparedStatement_execute(FilterChain chain, PreparedStatementProxy statement) throws SQLException {
        try {
            String sql = statement.getBatchSql();
            // 不输出无意义的内容
            if (sql.isEmpty()) {
                return true;
            }
            int parametersSize = statement.getParametersSize();
            if (parametersSize > 0) {
                List<Object> parameters = new ArrayList<>(parametersSize);
                for (int i = 0; i < parametersSize; ++i) {
                    JdbcParameter jdbcParam = statement.getParameter(i);
                    parameters.add(jdbcParam != null ? jdbcParam.getValue() : null);
                }
                // 这里可以使用数据库类型常量
                String dbType = statement.getConnectionProxy().getDirectDataSource().getDbType();
                sql = SQLUtils.format(sql, DbType.valueOf(dbType), parameters, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
            }
            // 打印sal
            printSQL(sql);
        } catch (Exception e) {
        }

        return super.preparedStatement_execute(chain, statement);
    }

    public void printSQL(String sql) {
        String sb = "\n"
                + sql.trim()
                + "\n--------------------------------------------------------------------------------\n";
        System.err.println(sb);
    }
}
